﻿using FRMS.DAL;
using FRMS.Model;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;

namespace FRMS.BUS
{
    public class AuditBUS
    {
        public ResponseMessage QueryAuditList(FrmsAuditInfo frmsAuditInfo)
        {
            ResponseMessage message = new ResponseMessage();
            AuditDAL da = new AuditDAL();
            message.errcode = 0;
            message.data = da.QueryFrmsAuditInfo(frmsAuditInfo);
            message.total = da.QueryFrmsAuditInfoCount(frmsAuditInfo);

            return message;
        }

        public ResponseMessage UpdateAuditState(FrmsAuditInfo frmsAuditInfo)
        {
            ResponseMessage message = new ResponseMessage();
            AuditDAL da = new AuditDAL();

            bool result = da.UpdateAuditState(frmsAuditInfo);
            if (result)
            {
                FrmsAuditInfo frmsAudit = da.LoadFrmsAuditInfo(frmsAuditInfo.id);
                SyncAuditState(frmsAudit);
                message.errcode = 0;
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "同步审核记录失败";
            }

            return message;
        }

        public ResponseMessage QueryAuditOwner(FrmsAuditInfo frmsAuditInfo)
        {
            ResponseMessage message = new ResponseMessage();
            AuditDAL da = new AuditDAL();
            message.errcode = 0;
            message.data = da.QueryOwnerByAudit(frmsAuditInfo);

            return message;
        }

        public ResponseMessage BindOwner(FrmsAuditInfo frmsAuditInfo)
        {
            ResponseMessage message = new ResponseMessage();
            AuditDAL da = new AuditDAL();
            VoucherDAL voucherDAL = new VoucherDAL();

            bool result = da.BindOwner(frmsAuditInfo);
            if (result)
            {
                VoucherInfo voucherInfo = new VoucherInfo();
                voucherInfo.OwnerID = frmsAuditInfo.ownerId;
                List<VoucherInfo> voucherInfos = voucherDAL.QueryVoucherList(voucherInfo);

                foreach (var item in voucherInfos)
                {
                    try
                    {
                        QRVoucher qRVoucher = new QRVoucher();
                        qRVoucher.AuditId = frmsAuditInfo.auditid;
                        qRVoucher.DeviceId = item.DeviceID;
                        qRVoucher.AuthorizedFloor = item.AuthorizedFloor;
                        qRVoucher.EffectiveStarttime = item.EffectiveStarttime;
                        qRVoucher.EffectiveEndtime = item.EffectiveEndtime;
                        qRVoucher.projectID = item.projectID;
                        ResponseMessage re_2 = AddQRVoucher(qRVoucher);
                        if (re_2.errcode == 0)
                        {

                        }
                    }
                    catch
                    {

                    }
                }

                //try
                //{
                //    OwnerDAL ownerDAL = new OwnerDAL();
                //    int projectid = ownerDAL.LoadOwnerInfo(frmsAuditInfo.ownerId).projectID;
                //    ProjectDAL projectDAL = new ProjectDAL();
                //    ProjectInfo projectInfo = projectDAL.LoadProject(projectid);
                //    qRCodeVoucherInfo.ProjectKey = projectInfo.project_key;
                //    string re = HttpClientPost(projectInfo.server_addr + "/api/Request/UpdateAudit", qRCodeVoucherInfo);
                //    QRCodeVoucherInfoReturn qRCodeReturn = JsonConvert.DeserializeObject<QRCodeVoucherInfoReturn>(re);
                //    if (qRCodeReturn != null && qRCodeReturn.code == 0 && qRCodeReturn.method == "UpdateAudit")
                //    {
                //        AuditDAL auditDAL = new AuditDAL();
                //        foreach (var item in qRCodeReturn.data)
                //        {
                //            bool re2 = auditDAL.UpdateSyncState(item);
                //        }
                //    }

                //}
                //catch (Exception ex)
                //{
                //    message.errcode = 1;
                //    message.errmsg = "同步二维码凭证异常";
                //}

                message.errcode = 0;
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "绑定业主失败";
            }

            return message;
        }

        public ResponseMessage AddOwner(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerDAL da = new OwnerDAL();
            AuditDAL auditDAL = new AuditDAL();
            OwnerBUS ownerBUS = new OwnerBUS();
            if (string.IsNullOrEmpty(ownerInfo.UUID))
            {
                ownerInfo.UUID = ownerBUS.GetUUID(ownerInfo.projectID);
            }

            if (string.IsNullOrEmpty(ownerInfo.CardNO))
            {
                ownerInfo.CardNO = ownerBUS.GetCardNo();
            }

            int result = da.AddQRCodeOwner(ownerInfo);
            if (result > 0)
            {
                FrmsAuditInfo frmsAuditInfo = new FrmsAuditInfo();
                frmsAuditInfo.ownerId = result;
                frmsAuditInfo.id = ownerInfo.auditrecordid;
                bool result2 = auditDAL.BindOwner(frmsAuditInfo);
                if (result2)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "绑定业主信息失败";
                }

            }
            else
            {
                message.errcode = 1;
                message.errmsg = "新增业主信息失败";
            }

            return message;
        }

        public void SyncAuditState(FrmsAuditInfo frmsAuditInfo)
        {

            try
            {
                VoucherBUS voucherBUS = new VoucherBUS();
                QRCodeAudit qRCodeAudit = new QRCodeAudit();
                qRCodeAudit.method = "UpdateAuditState";
                qRCodeAudit.ProjectKey = frmsAuditInfo.project_key;
                List<QRCodeAuditData> list = new List<QRCodeAuditData>();
                QRCodeAuditData qRCodeAuditData = new QRCodeAuditData();
                qRCodeAuditData.AuditID = frmsAuditInfo.auditid;
                qRCodeAuditData.AuditStatus = frmsAuditInfo.auditStatus;
                qRCodeAuditData.AuditStatusTime = frmsAuditInfo.auditTime;
                list.Add(qRCodeAuditData);
                qRCodeAudit.data = list;
                string re = voucherBUS.HttpClientPost(frmsAuditInfo.server_addr + "/api/Request/UpdateAuditState", qRCodeAudit);
                QRCodeAuditReturn qRCodeReturn = JsonConvert.DeserializeObject<QRCodeAuditReturn>(re);
                if (qRCodeReturn != null && qRCodeReturn.code == 0 && qRCodeReturn.method == "UpdateAuditState")
                {
                    AuditDAL auditDAL = new AuditDAL();
                    foreach (var item in qRCodeReturn.data)
                    {
                        if (item.result == 0)
                        {
                            bool result = auditDAL.UpdateAuditSync(item.AuditID);
                            if (result && frmsAuditInfo.auditStatus == 2)
                            {
                                List<QRVoucher> qRVouchers = auditDAL.QueryQRVoucher(frmsAuditInfo.auditid);
                                if (qRVouchers != null && qRVouchers.Count > 0)
                                {
                                    QRCodeVoucherInfo qRCodeVoucherInfo = new QRCodeVoucherInfo();

                                    qRCodeVoucherInfo.method = "UpdateAudit";
                                    List<QRCodeVoucherInfoData> qRCodeVoucherInfoDatas = new List<QRCodeVoucherInfoData>();

                                    foreach (var qr in qRVouchers)
                                    {
                                        QRCodeVoucherInfoData codeVoucherInfoData = new QRCodeVoucherInfoData();
                                        codeVoucherInfoData.auditid = frmsAuditInfo.auditid;
                                        codeVoucherInfoData.deviceName = qr.DeviceName;
                                        codeVoucherInfoData.deviceNo = qr.DeviceNO;

                                        List<QRCodeVoucherInfoFloorInfo> floor_list = new List<QRCodeVoucherInfoFloorInfo>();
                                        string[] dfloors = qr.AuthorizedFloor.Split(',');
                                        string[] array = qr.FloorInfo.Split(',');
                                        string[] pfloors = qr.pFloorInfo.Split(',');
                                        foreach (var value in dfloors)
                                        {
                                            QRCodeVoucherInfoFloorInfo qRCodeVoucherInfoData = new QRCodeVoucherInfoFloorInfo();
                                            qRCodeVoucherInfoData.startTime = qr.EffectiveStarttime;
                                            qRCodeVoucherInfoData.endTime = qr.EffectiveEndtime;
                                            qRCodeVoucherInfoData.dfloor = value;
                                            int index = array.ToList().IndexOf(value);
                                            if (index >= 0)
                                            {
                                                int pfloor = Convert.ToInt32(pfloors[index]);
                                                string data = GetCemsCallCmd(pfloor, qr.LadderID.ToString(), qr.EffectiveStarttime, qr.EffectiveEndtime);
                                                qRCodeVoucherInfoData.pfloor = pfloor;
                                                qRCodeVoucherInfoData.qrcodeData = data;
                                            }
                                            floor_list.Add(qRCodeVoucherInfoData);
                                        }
                                        codeVoucherInfoData.floor = floor_list;
                                        qRCodeVoucherInfoDatas.Add(codeVoucherInfoData);
                                    }
                                    qRCodeVoucherInfo.data = qRCodeVoucherInfoDatas;

                                    try
                                    {
                                        OwnerDAL ownerDAL = new OwnerDAL();
                                        int projectid = ownerDAL.LoadOwnerInfo(frmsAuditInfo.ownerId).projectID;
                                        ProjectDAL projectDAL = new ProjectDAL();
                                        ProjectInfo projectInfo = projectDAL.LoadProject(projectid);
                                        qRCodeVoucherInfo.ProjectKey = projectInfo.project_key;
                                        string response = HttpClientPost(projectInfo.server_addr + "/api/Request/UpdateAudit", qRCodeVoucherInfo);
                                        QRCodeVoucherInfoReturn qRCodeReturn2 = JsonConvert.DeserializeObject<QRCodeVoucherInfoReturn>(response);
                                        if (qRCodeReturn2 != null && qRCodeReturn2.code == 0 && qRCodeReturn2.method == "UpdateAudit")
                                        {
                                            foreach (var qrdata in qRCodeReturn2.data)
                                            {
                                                bool re2 = auditDAL.UpdateSyncState(qrdata);
                                            }
                                        }

                                    }
                                    catch (Exception ex)
                                    {

                                    }
                                }


                            }
                        }
                    }
                }


            }
            catch
            {

            }

        }

        public ResponseMessage DeleteAudit(FrmsAuditInfo frmsAuditInfo)
        {
            ResponseMessage message = new ResponseMessage();
            AuditDAL da = new AuditDAL();

            bool result = DeleteAuditRecord(frmsAuditInfo);
            if (result)
            {
                message.errcode = 0;
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "删除审核记录失败";
            }

            return message;
        }

        public bool DeleteAuditRecord(FrmsAuditInfo frmsAuditInfo)
        {
            bool result = false;
            try
            {
                VoucherBUS voucherBUS = new VoucherBUS();
                QRCodeAudit qRCodeAudit = new QRCodeAudit();
                qRCodeAudit.method = "DeleteAuditState";
                qRCodeAudit.ProjectKey = frmsAuditInfo.project_key;
                List<QRCodeAuditData> list = new List<QRCodeAuditData>();
                QRCodeAuditData qRCodeAuditData = new QRCodeAuditData();
                qRCodeAuditData.AuditID = frmsAuditInfo.auditid;
                list.Add(qRCodeAuditData);
                qRCodeAudit.data = list;
                string re = voucherBUS.HttpClientPost(frmsAuditInfo.server_addr + "/api/Request/DeleteAuditState", qRCodeAudit);
                QRCodeAuditReturn qRCodeReturn = JsonConvert.DeserializeObject<QRCodeAuditReturn>(re);
                if (qRCodeReturn != null && qRCodeReturn.code == 0 && qRCodeReturn.method == "DeleteAuditState")
                {
                    AuditDAL auditDAL = new AuditDAL();
                    foreach (var item in qRCodeReturn.data)
                    {
                        if (item.result == 0)
                        {
                            result = auditDAL.DeleteAudit(item.AuditID);
                        }
                    }
                }
            }
            catch
            {
            }
            return result;
        }

        public ResponseMessage QueryQRVoucher(int auditid)
        {
            ResponseMessage message = new ResponseMessage();
            AuditDAL da = new AuditDAL();
            message.errcode = 0;
            message.data = da.QueryQRVoucher(auditid);

            return message;
        }

        public ResponseMessage AddQRVoucher(QRVoucher qRVoucher)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                AuditDAL auditDAL = new AuditDAL();

                List<QRVoucher> list = auditDAL.QueryQRVoucher(qRVoucher.AuditId);
                int qR_index = list.FindIndex(x => x.DeviceId == qRVoucher.DeviceId);
                bool result = false;
                if (qR_index > -1)
                {
                    result = auditDAL.updateQRVoucher(qRVoucher);
                }
                else
                {
                    result = auditDAL.addQRVoucher(qRVoucher);
                }

                if (result)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "新增二维码凭证失败";
                }
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "新增二维码凭证异常";
            }
            return message;
        }

        //public ResponseMessage UpdateQRVoucher(QRVoucher qRVoucher)
        //{
        //    ResponseMessage message = new ResponseMessage();
        //    try
        //    {
        //        AuditDAL auditDAL = new AuditDAL();
        //        bool result = auditDAL.addQRVoucher(qRVoucher);
        //        if (result)
        //        {
        //            message.errcode = 0;
        //        }
        //        else
        //        {
        //            message.errcode = 1;
        //            message.errmsg = "新增二维码凭证失败";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        message.errcode = 1;
        //        message.errmsg = "新增二维码凭证异常";
        //    }
        //    return message;
        //}

        public ResponseMessage DelQRVoucher(QRVoucher qRVoucher)
        {
            AuditDAL auditDAL = new AuditDAL();
            ResponseMessage message = new ResponseMessage();
            try
            {
                string response = DeleteQRCodeVoucher(qRVoucher);
                QRCodeVoucherInfoReturn qRCodeReturn = JsonConvert.DeserializeObject<QRCodeVoucherInfoReturn>(response);
                if (qRCodeReturn != null && qRCodeReturn.code == 0 && qRCodeReturn.method == "DeleteVoucher")
                {
                    AuditDAL voucherDAL = new AuditDAL();
                    foreach (var item in qRCodeReturn.data)
                    {
                        bool result = voucherDAL.DeleteQRVoucher(qRVoucher.ID);
                        if (!result)
                        {
                            message.errcode = 1;
                            message.errmsg = "删除失败";
                            return message;
                        }
                    }
                }
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "删除异常";
            }
            return message;
        }

        public ResponseMessage SyncQRVoucher(QRVoucher qRVoucher)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                QRCodeVoucherInfo qRCodeVoucherInfo = new QRCodeVoucherInfo();
                qRCodeVoucherInfo.ProjectKey = qRVoucher.project_key;
                qRCodeVoucherInfo.method = "UpdateAudit";
                List<QRCodeVoucherInfoData> qRCodeVoucherInfoDatas = new List<QRCodeVoucherInfoData>();
                QRCodeVoucherInfoData codeVoucherInfoData = new QRCodeVoucherInfoData();
                codeVoucherInfoData.auditid = qRVoucher.AuditId;
                codeVoucherInfoData.deviceName = qRVoucher.DeviceName;
                codeVoucherInfoData.deviceNo = qRVoucher.DeviceNO;

                List<QRCodeVoucherInfoFloorInfo> floor_list = new List<QRCodeVoucherInfoFloorInfo>();
                string[] dfloors = qRVoucher.AuthorizedFloor.Split(',');
                string[] array = qRVoucher.FloorInfo.Split(',');
                string[] pfloors = qRVoucher.pFloorInfo.Split(',');
                foreach (var value in dfloors)
                {
                    QRCodeVoucherInfoFloorInfo qRCodeVoucherInfoData = new QRCodeVoucherInfoFloorInfo();
                    qRCodeVoucherInfoData.startTime = qRVoucher.EffectiveStarttime;
                    qRCodeVoucherInfoData.endTime = qRVoucher.EffectiveEndtime;
                    qRCodeVoucherInfoData.dfloor = value;
                    int index = array.ToList().IndexOf(value);
                    if (index >= 0)
                    {
                        int pfloor = Convert.ToInt32(pfloors[index]);
                        string data = GetCemsCallCmd(pfloor, qRVoucher.LadderID.ToString(), qRVoucher.EffectiveStarttime, qRVoucher.EffectiveEndtime);
                        qRCodeVoucherInfoData.pfloor = pfloor;
                        qRCodeVoucherInfoData.qrcodeData = data;
                    }
                    floor_list.Add(qRCodeVoucherInfoData);
                }
                codeVoucherInfoData.floor = floor_list;
                qRCodeVoucherInfoDatas.Add(codeVoucherInfoData);
                qRCodeVoucherInfo.data = qRCodeVoucherInfoDatas;
                string re = HttpClientPost(qRVoucher.server_addr + "/api/Request/UpdateAudit", qRCodeVoucherInfo);
                QRCodeVoucherInfoReturn qRCodeReturn = JsonConvert.DeserializeObject<QRCodeVoucherInfoReturn>(re);
                if (qRCodeReturn != null && qRCodeReturn.code == 0 && qRCodeReturn.method == "UpdateAudit")
                {
                    AuditDAL voucherDAL = new AuditDAL();
                    foreach (var item in qRCodeReturn.data)
                    {
                        bool result = voucherDAL.UpdateSyncState(item);
                    }
                }

            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "同步二维码凭证异常";
            }
            return message;
        }

        public string HttpClientPost(string url, object datajson)
        {
            HttpClient httpClient = new HttpClient();//http对象
            //表头参数
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //转为链接需要的格式
            HttpContent httpContent = new JsonContent(datajson);
            //请求
            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    return t.Result;
                }
            }
            return "";
        }

        public string DeleteQRCodeVoucher(QRVoucher qRVoucher)
        {
            try
            {
                OwnerDAL ownerDAL = new OwnerDAL();
                QRCodeVoucherInfo qRCodeVoucherInfo = new QRCodeVoucherInfo();
                qRCodeVoucherInfo.ProjectKey = qRVoucher.project_key;
                qRCodeVoucherInfo.method = "DeleteVoucher";
                List<QRCodeVoucherInfoData> qRCodeVoucherInfoDatas = new List<QRCodeVoucherInfoData>();
                QRCodeVoucherInfoData codeVoucherInfoData = new QRCodeVoucherInfoData();
                codeVoucherInfoData.auditid = qRVoucher.AuditId;
                codeVoucherInfoData.deviceName = qRVoucher.DeviceName;
                codeVoucherInfoData.deviceNo = qRVoucher.DeviceNO;

                List<QRCodeVoucherInfoFloorInfo> floor_list = new List<QRCodeVoucherInfoFloorInfo>();
                qRCodeVoucherInfoDatas.Add(codeVoucherInfoData);
                qRCodeVoucherInfo.data = qRCodeVoucherInfoDatas;
                string re = HttpClientPost(qRVoucher.server_addr + "/api/Request/DeleteVoucher", qRCodeVoucherInfo);
                return re;
            }
            catch
            {
                return "";
            }
        }

        public string GetCallCmd(int Pfloor, string ladderid)
        {
            string DefaultFloor = "";
            string updateFloorTOHex = "";
            string dd;
            for (int i = 1; i <= 80; i++)
            {
                DefaultFloor = DefaultFloor + "0";
            }
            DefaultFloor = DefaultFloor.Remove(80 - Pfloor, 1).Insert(80 - Pfloor, "1");
            string updateFloor = DefaultFloor.Substring(64, 16) + DefaultFloor.Substring(48, 16) + DefaultFloor.Substring(32, 16) + DefaultFloor.Substring(16, 16) + DefaultFloor.Substring(0, 16);
            //string updateFloor = DefaultFloor;
            for (int k = 0; k < 80; k += 8)
            {
                updateFloorTOHex = updateFloorTOHex + string.Format("{0:X}", Convert.ToInt32(updateFloor.Substring(k, 8), 2)).PadLeft(2, '0');
            }
            //楼层点亮
            dd = "008B0000001B" + Convert.ToInt32(ladderid).ToString("X").PadLeft(2, '0') + "100019000A14" + updateFloorTOHex + "00000000000000000000";
            return dd;
        }

        public string GetCemsCallCmd(int Pfloor, string ladderid, string starttime, string endtime)
        {
            string DefaultFloor = "";
            string updateFloorTOHex = "";
            string dd;
            for (int i = 1; i <= 80; i++)
            {
                DefaultFloor = DefaultFloor + "0";
            }
            DefaultFloor = DefaultFloor.Remove(80 - Pfloor, 1).Insert(80 - Pfloor, "1");
            string updateFloor = DefaultFloor.Substring(64, 16) + DefaultFloor.Substring(48, 16) + DefaultFloor.Substring(32, 16) + DefaultFloor.Substring(16, 16) + DefaultFloor.Substring(0, 16);
            //string updateFloor = DefaultFloor;
            for (int k = 0; k < 80; k += 8)
            {
                updateFloorTOHex = updateFloorTOHex + string.Format("{0:X}", Convert.ToInt32(updateFloor.Substring(k, 8), 2)).PadLeft(2, '0');
            }
            //楼层点亮
            dd = "008B0000001B" + Convert.ToInt32(ladderid).ToString("X").PadLeft(2, '0') + "100019000A14" + updateFloorTOHex + "00000000000000000000" + Convert.ToDateTime(starttime).ToString("yyyyMMddHHmmss") + Convert.ToDateTime(endtime).ToString("yyyyMMddHHmmss");
            return dd;
        }
    }
}
